#include "chat_client.h"

#include <string>

#include "netlib/base/logger.h"

ChatClient::ChatClient(net::EventLoop* loop, const net::InetAddress& serv_addr) :
    loop_(loop), client_(loop, serv_addr, "ChatClient"),
    codec_([this](const net::TcpConnectionPtr& conn, const std::string& msg, Timestamp time) {
	    OnStringMessage(conn, msg, time);
    }) {
	client_.SetConnectionCallback(
	    [this](const net::TcpConnectionPtr& conn) { OnConnection(conn); });
	client_.SetMessageCallback(
	    [&codec = codec_](const net::TcpConnectionPtr& conn, net::Buffer* buf, Timestamp time) {
		    codec.OnMessage(conn, buf, time);
	    });
	// client_.enableRetry();
}

void ChatClient::Write(const std::string& msg) {
	MutexLockGuard lock(mutex_);
	if (connect_) {
		codec_.Send(connect_, msg);
	}
}

void ChatClient::OnConnection(const net::TcpConnectionPtr& conn) {
	LOG_INFO << "ChatServer : " << conn->LocalAddress().ToIpPort() << "<->"
	         << conn->PeerAddress().ToIpPort() << " is " << (conn->Connected() ? "UP" : "DOWN");
	MutexLockGuard lock(mutex_);
	if (conn->Connected()) {
		connect_ = conn;
	} else {
		connect_.reset();
	}
}

void ChatClient::OnStringMessage(const net::TcpConnectionPtr& conn,
                                 const std::string& msg,
                                 Timestamp time) {
	printf("<<< %s\n", msg.c_str());
}
